"use strict";

const shell = require("shelljs");
const ora = require("ora");
const chalk = require("chalk");
const fs = require("fs");
const pwd = shell.pwd();
const projectUrl = "https://gitee.com/xieyejiang/create-react-ts-app.git";

module.exports = name => {
  const spinner = ora();
  const fullPath = `${pwd}/${name}/`;
  spinner.start(`下载位置：${fullPath}`);
  spinner.start("正在生成···");
  new Promise((resolve, reject) => {
    shell.exec(`git clone ${projectUrl} ${name}`, code => {
      if (code === 0) {
        shell.rm("-rf", `${fullPath}.git`);
        resolve(code);
      } else {
        reject(code);
      }
    });
  })
    .then(() => {
      const originData = fs.readFileSync(`${fullPath}package.json`, "utf-8");
      let targetData = JSON.parse(originData);
      targetData.version = "0.1.0";
      targetData.name = name;
      const result = JSON.stringify(targetData, null, 4);
      fs.writeFileSync(`${fullPath}package.json`, result);
      console.log("");
      console.log(chalk.green("项目创建成功."));
      spinner.stop();
      shell.exit();
    })
    .catch(err => {
      spinner.stop();
      console.log(chalk.red("项目创建失败."));
      console.log("");
    });
};
